package com.attendance.common;


import com.attendance.entity.Employee;
import com.attendance.service.EmployeeService;
import com.attendance.util.JwtUtil;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;


@Component
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {


    @Autowired
    EmployeeService employeeService;
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        //获取token
        String token = request.getHeader("auth");
        if (!StringUtils.hasText(token)) {
            //如果不携带token
            response.setStatus(403);
return;
        }
        //解析token，获得userid
        Long userid ;

        try {
            Claims claims = JwtUtil.parseJwt(token);
         Integer empId = (Integer) claims.get("EmpId");
 Employee employee=employeeService.getById(Long.valueOf(empId));
            BaseContext.setEmployee(employee);
            filterChain.doFilter(request, response);
        } catch (Exception e) {
           response.setStatus(403);
return;
        }
        //TODO 获取权限信息封装到Authentication中

    }
}


